#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "goset.h"
#include "dialog_yp.h"
#include "dialog_sql.h"
#include "dialog_set.h"
#include "mysql.h"
#include "dialog_msbox.h"
#include "test_check.h"
#include "dialog_test.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->showMaximized();


    mysql::query_system(&buffer);//加载系统参数
    test_load();

    con_com=new com(&buffer);
    connect(this,SIGNAL(send_bush()),con_com,SLOT(run_time_out()));
    con_com->start();

    run_time=new QTimer;
    connect(run_time,SIGNAL(timeout()),this,SLOT(run_time_out()));

    bush_time=new QTimer;
    connect(bush_time,SIGNAL(timeout()),this,SLOT(bush_time_out()));
    bush_time->start(500);

    if(buffer.system.system_user==nullptr)
        this->setWindowTitle(QString("未注册                          技术支持：睿青(广州)科技有限公司"));
    else
        this->setWindowTitle(QString("注册：%1                           技术支持：睿青(广州)科技有限公司").arg(buffer.system.system_user));


    send_sata(17,false);//发送第一次信息
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::bush_time_out()
{
    //刷新图表
    ui->test_tn->setText(QString("%1℃").arg(buffer.buf.buf_tn,0,'f',4));
    ui->test_frl->setText(QString("%1J").arg(buffer.buf.buf_fr,0,'f',1));
    ui->test_rrl->setText(QString("%1J/K").arg(buffer.buf.buf_rr,0,'f',1));

    ui->test_tc->setText(QString("%1℃").arg(buffer.buf.buf_tc,0,'f',4));
    ui->test_tl->setText(QString("%1℃").arg(buffer.buf.buf_tl,0,'f',4));
    ui->test_th->setText(QString("%1℃").arg(buffer.buf.buf_th,0,'f',4));
    ui->temp_water->setText(QString("内筒水温: %1℃").arg(buffer.buf.buf_tn,0,'f',4));
    ui->temp_waitong->setText(QString("外筒温度: %1℃").arg(buffer.temp_waitong,0,'f',4));

    if(buffer.fire_con==0)      go_logo[4]->set_round_color(QColor(0,255,0));
    else if(buffer.fire_con==1) go_logo[4]->set_round_color(QColor(255,0,0));


}


void MainWindow::send_sata(int ID,bool ON)
{
    if((ID<28) && (ON))         buffer.write_buf[ID]=0x10;
    else if((ID<28) && (!ON))   buffer.write_buf[ID]=0x00;

    QByteArray sm; QDataStream dataStream(&sm,QIODevice::WriteOnly);
    for(int i=0;i<28;i++) dataStream << buffer.write_buf[i];
    buffer.writeData.append(sm);
}

void MainWindow::on_reset_clicked()
{
    int row=ui->comboBox->currentIndex();
    buffer.data.data_index=QString("%1").arg(row+1);
    int ret=Dialog_msbox::show(1,1,"重置","重置试验",QString("请注意，是否重置第%1次试验，继续将删除当前数据?").arg(row+1));
    if(ret==1)
    {
        ui->tableWidget->setItem(row,3,new QTableWidgetItem(""));
        ui->tableWidget->setItem(row,4,new QTableWidgetItem(""));
        ui->tableWidget->setItem(row,5,new QTableWidgetItem(""));
        ui->tableWidget->setItem(row,6,new QTableWidgetItem(""));

        //删除历史数据
        test_temp data;
        data.test_id=buffer.info.test_id;
        data.test_index=buffer.data.data_index;
        mysql::del_test_temp(data);


        buffer.buf.buf_ci.clear();
        buffer.buf.buf_ct.clear();

        ui->plot->graph(0)->setData(buffer.buf.buf_ci,buffer.buf.buf_ct);
        ui->plot->show();
        ui->plot->replot();

    }
}

void MainWindow::on_start_clicked()
{
    if(ui->start->text()=="启动")
    {
        if(buffer.info.test_id==nullptr)
        {
            Dialog_msbox::show(2,0,"错误","error",QString("试样编号为空，请先新建或加载试样信息！"));
            return;
        }


        int row=ui->comboBox->currentIndex();
        int ret=Dialog_msbox::show(1,1,"开始运行","Start running",QString("请注意，是否开始第%1次试验?").arg(row+1));

        if(ret==1)
        {

            int index=ui->comboBox->currentIndex();
            double buf_zg=0,buf_tjwg=0,buf_bjsg=0;
            if(ui->tableWidget->item(index,3)!=nullptr)buf_zg=ui->tableWidget->item(index,3)->text().toDouble();
            if(ui->tableWidget->item(index,4)!=nullptr)buf_tjwg=ui->tableWidget->item(index,4)->text().toDouble();
            if(ui->tableWidget->item(index,5)!=nullptr)buf_bjsg=ui->tableWidget->item(index,5)->text().toDouble();

            if(buf_zg>0)buffer.buf.buf_zg=buf_zg;
            else        buffer.buf.buf_zg=0;

            if(buf_tjwg>0)buffer.buf.buf_tjwg=buf_tjwg;
            else          buffer.buf.buf_tjwg=0;

            if(buf_bjsg>0)buffer.buf.buf_bjsg=buf_bjsg;
            else          buffer.buf.buf_bjsg=0;

            ui->tableWidget->item(index,6)->setText(QString("%1").arg(buffer.system.system_jrs));

            buffer.data.data_index=QString("%1").arg(index+1);

            //刷新状态
            get_bush();

            //禁止写入试验数据

            ui->tableWidget->item(index,3)->setFlags(Qt::NoItemFlags);
            ui->tableWidget->item(index,4)->setFlags(Qt::NoItemFlags);
            ui->tableWidget->item(index,5)->setFlags(Qt::NoItemFlags);
            ui->tableWidget->item(index,6)->setFlags(Qt::NoItemFlags);

            if(buffer.buf.buf_zg<0.001)
            {
                Dialog_msbox::show(2,0,"错误","error",QString("第%1次试样质量(g)填写错误,请重新检查！").arg(index));              
                ui->tableWidget->setItem(index,3,new QTableWidgetItem(""));
                ui->tableWidget->setItem(index,4,new QTableWidgetItem(""));
                ui->tableWidget->setItem(index,5,new QTableWidgetItem(""));
                ui->tableWidget->setItem(index,6,new QTableWidgetItem(""));

                return;
            }

            run_time->start(1000);            
            water_time=0;
            ui->start->setText("停止");
            state_id=1;
            ui->comboBox->setEnabled(false);
            ui->reset->setEnabled(false);
            water_loop_test_state = 0;//试验前先做水循环
            time_add=0;

            //删除历史数据
            test_temp data;
            data.test_id=buffer.info.test_id;
            data.test_index=buffer.data.data_index;
            mysql::del_test_temp(data);

            //写入开始时间
            QString d1=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            ui->tableWidget->item(index,9)->setText(d1);
        }

    }else
    {
        int row=ui->comboBox->currentIndex();
        int ret=Dialog_msbox::show(1,1,"停止运行","Stop running",QString("请注意，准备停止第%1次试验，是否继续停止?").arg(row+1));
        if(ret==1){
            time_stop=0;
            state_id=7;
        }
    }
}
void MainWindow::run_time_out()
{
    //刷新计时
    int h=0,m=0,s=0;
    h=time_add/3600;
    m=(time_add%3600)/60;
    s=time_add%60;

    ui->lcdNumber->display(QString("%1:%2:%3").arg(h,2,10,QLatin1Char('0'))
                           .arg(m,2,10,QLatin1Char('0')).arg(s,2,10,QLatin1Char('0')));

    int index=ui->comboBox->currentIndex();

    //状态机判断

    if(state_id==1)//注水
    {

        send_sata(9,true);//开始搅拌
        if(water_loop_test_state == 0)
        {
            send_sata(10,true);//开始注水
            go_logo[state_id]->set_Text("注水");
            go_logo[state_id]->gif_run=true;
            go_logo[state_id]->set_gif(5);
            go_logo[state_id]->set_val(30);

            water_loop_test_state=10;
            water_time=buffer.system.system_zsti+5;
            QTimer::singleShot(buffer.system.system_zsti*1000,this,[=]
            {
                send_sata(10,false);//停止注水
                //注水完成后判断外筒与内筒温差,满足条件，进入下一步，则否开始排水
                if((buffer.temp_waitong - buffer.buf.buf_tn < 0.15) &&
                        (buffer.temp_waitong - buffer.buf.buf_tn > -0.15))
                {
                    go_logo[state_id]->gif_run=false;
                    go_logo[state_id]->gif_start=90;
                    go_logo[state_id]->set_gif(0);
                    go_logo[state_id]->set_val(100);
                    state_id=2;

                } else water_loop_test_state =2; //不满足条件开始排水
            });

        }
        else if(water_loop_test_state == 2)
        {
            send_sata(11,true); send_sata(13,true);
            go_logo[state_id]->set_Text("排水");
            //排水时间到后停止排水，并跳转到状态0;
            QTimer::singleShot((buffer.system.system_zsti+5)*1000,this,[=]
            {
                send_sata(11,false); send_sata(13,false);water_loop_test_state = 0;
            });
        }
    }
    else if(state_id==2)//搅拌
    {
        go_logo[state_id]->gif_run=true;
        go_logo[state_id]->set_gif(5);
        go_logo[state_id]->set_val(30);
        state_id=3;

        send_sata(9,true);//开始搅拌

        //初始化恒温曲线数据
        buffer.buf.buf_t.clear();
        buffer.buf.buf_i.clear();

        //初始化试验曲线数据
        con_com->run_timeadd=0;
        buffer.buf.buf_ci.clear();
        buffer.buf.buf_ct.clear();

    }
    else if(state_id==3)//准备10分钟内温度差小于0.01开始点火
    {
        go_logo[state_id]->gif_run=true;
        go_logo[state_id]->set_gif(5);
        go_logo[state_id]->set_val(30);

        qDebug()<<buffer.buf.buf_t.count()<<buffer.buf.buf_tc;

        if((buffer.buf.buf_t.count()>598)  && (buffer.buf.buf_tc<0.02))//(buffer.buf.buf_t.count()>599)  &&
        {
            go_logo[state_id]->gif_run=false;
            go_logo[state_id]->gif_start=90;
            go_logo[state_id]->set_gif(0);
            go_logo[state_id]->set_val(100);

            ui->tableWidget->setItem(index,1,new QTableWidgetItem(QString("%1").arg(buffer.buf.buf_tn+273.15)));//起点温度（开尔文）
            buffer.data.data_t1=buffer.buf.buf_tn+273.15;
            state_id=4;
        }
    }
    else if(state_id==4)//点火
    {
        go_logo[state_id]->gif_run=false;
        go_logo[state_id]->gif_start=90;
        go_logo[state_id]->set_gif(0);
        go_logo[state_id]->set_val(100);
        time_fire=0;
        state_id=5;


        send_sata(8,true);//开始点火

        //初始化恒温曲线数据
        buffer.buf.buf_t.clear();
        buffer.buf.buf_i.clear();

    }
    else if(state_id==5)//测量，10分钟内温度差小于0.02试验停止或当前温度小于最高温度0.01
    {
        go_logo[state_id]->gif_run=true;
        go_logo[state_id]->set_gif(5);
        go_logo[state_id]->set_val(30);

        time_fire++;

        if(time_fire>5)//停止点火
        {
            send_sata(8,false);//停止点火
            time_fire=0;
        }


        if((buffer.info.test_id.mid(0,3)=="cal")  && (buffer.buf.buf_tn + 273.15 - buffer.data.data_t1>1))
        {
            //比热容=苯甲酸热值*质量/(当前温度-起点温度)
            buffer.buf.buf_rr= (buffer.system.system_bjs*buffer.buf.buf_zg - buffer.system.system_jrs)
                    /(buffer.buf.buf_tn + 273.15 - buffer.data.data_t1);

            buffer.buf.buf_fr=buffer.system.system_bjs * buffer.buf.buf_zg;
            ui->tableWidget->item(index,7)->setText(QString("%1").arg(buffer.buf.buf_rr));

        }else if(buffer.info.test_id.mid(0,3)!="cal")
        {
            //总热值=比热容*(当前温度-起点温度)-发热丝热值-苯甲酸热值-添加物热值(香烟叶)/质量kg

            buffer.buf.buf_fr=buffer.buf.buf_rr * (buffer.buf.buf_tn + 273.15 - buffer.data.data_t1)
                    -(buffer.system.system_jrs + buffer.system.system_bjs*buffer.buf.buf_bjsg
                      + buffer.system.system_tjw1 * buffer.buf.buf_tjwg);


            ui->tableWidget->item(index,7)->setText(QString("%1").arg(buffer.system.system_rrl1 + buffer.system.system_rrl2));
            ui->tableWidget->item(index,8)->setText(QString("%1").arg(buffer.buf.buf_fr / buffer.buf.buf_zg));
        }



        if((buffer.buf.buf_t.count()>598)  && ( (buffer.buf.buf_tc<0.02) || (buffer.buf.buf_th-buffer.buf.buf_tn>0.01) ))
        {
            go_logo[state_id]->gif_run=false;
            go_logo[state_id]->gif_start=90;
            go_logo[state_id]->set_gif(0);
            go_logo[state_id]->set_val(100);


            ui->tableWidget->setItem(index,2,new QTableWidgetItem(QString("%1").arg(buffer.buf.buf_tn+273.15)));//终止点温度（开尔文）
            buffer.data.data_t2=buffer.buf.buf_tn+273.15;            


            state_id=6;
        }
    }
    else if(state_id==6)//停止
    {
        go_logo[state_id]->gif_start=90;
        go_logo[state_id]->set_gif(0);
        go_logo[state_id]->set_val(100);

        ui->start->setText("正在停止");

        send_sata(9,false);//停止搅拌
        send_sata(8,false);//停止点火
        for(int i=1;i<7;i++) go_logo[1]->gif_run=false;//更新状态

        QString d2=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        ui->tableWidget->item(index,10)->setText(d2);


        //保存数据
        test_data data;
        data.data_id=buffer.info.test_id;
        data.data_index=QString("%1").arg(index+1);
        data.data_t1  =ui->tableWidget->item(index,1)->text().toDouble();
        data.data_t2  =ui->tableWidget->item(index,2)->text().toDouble();
        data.data_sum =ui->tableWidget->item(index,3)->text().toDouble();
        data.data_tjw =ui->tableWidget->item(index,4)->text().toDouble();
        data.data_bjs =ui->tableWidget->item(index,5)->text().toDouble();
        data.data_jrs =ui->tableWidget->item(index,6)->text().toDouble();
        data.data_dtl =0;
        data.data_sdl =ui->tableWidget->item(index,7)->text().toDouble();
        data.data_zp  =ui->tableWidget->item(index,8)->text().toDouble();
        data.data_d1  =ui->tableWidget->item(index,9)->text();
        data.data_d2  =ui->tableWidget->item(index,10)->text();
        mysql::INSERT_test_data(data);

        //搅拌
        go_logo[2]->gif_run=false;
        go_logo[2]->gif_start=90;
        go_logo[2]->set_gif(0);
        go_logo[2]->set_val(100);


        time_stop=0;
        state_id=7;
    }
    else if(state_id==7)//排水
    {
        go_logo[7]->set_Text("排水");
        go_logo[state_id]->gif_run=true;
        go_logo[state_id]->set_gif(5);
        go_logo[state_id]->set_val(30);
        water_time--;


        send_sata(11,true);//开始排水
        send_sata(13,true);//开始排水

        if(water_time < 0)//排水结束
        {


            send_sata(11,false);//开始排水
            send_sata(13,false);//开始排水
            go_logo[7]->set_Text("均温");

            //根据温差计算制冷时长
            double tc=buffer.data.data_t2-buffer.data.data_t1;
            refrigeration=buffer.temp_ctrl*tc;

            state_id=8;
        }


    }
    else if(state_id==8)
    {
        if(refrigeration > 0)
        {
            send_sata(16,true);//开始制冷
            refrigeration--;

        }else//停止制冷
        {
            go_logo[7]->gif_run=false;
            go_logo[7]->gif_start=90;
            go_logo[7]->set_gif(0);
            go_logo[7]->set_val(100);
            send_sata(16,false);
            state_id=9;
            go_logo[7]->set_Text("结束");
        }
    }
    else if(state_id==9)
    {
        run_time->stop();

        ui->start->setText("启动");
        ui->comboBox->setEnabled(true);
        ui->reset->setEnabled(true);
    }

    if((state_id>2) && (state_id<6))
    {

        //发出刷新数据信号
        emit send_bush();

        //刷新曲线数据
        auto max = std::max_element(std::begin(buffer.buf.buf_ct), std::end(buffer.buf.buf_ct));//取容器内最大值
        auto min = std::min_element(std::begin(buffer.buf.buf_ct), std::end(buffer.buf.buf_ct));//取容器内最小值
        ui->plot->yAxis->setRange(*min-0.5,*max+0.5);
        ui->plot->xAxis->setRange(0,time_add+60);

        ui->plot->graph(0)->setData(buffer.buf.buf_ci,buffer.buf.buf_ct);
        ui->plot->show();
        ui->plot->replot();
    }


    time_add++;
}


void MainWindow::test_load()
{
    //状态表初始化
    //go_logo[0]=ui->test_0;
    go_logo[1]=ui->test_1;
    go_logo[2]=ui->test_2;
    go_logo[3]=ui->test_3;
    go_logo[4]=ui->test_4;
    go_logo[5]=ui->test_5;
    go_logo[6]=ui->test_6;
    go_logo[7]=ui->test_7;

    QStringList txt;
    txt<<"冲洗"<<"注水"<<"搅拌"<<"准备"<<"点火"<<"测量"<<"停止"<<"排水";
    for(int i=1;i<8;i++)
    {
        go_logo[i]->set_round_wigth(2);
        go_logo[i]->set_round_color(QColor(0,255,0));
        go_logo[i]->set_val(10);
        go_logo[i]->set_Text(txt.at(i));
    }



    ui->lcdNumber->display("00:00:00");

     //曲线初始化
    ui->plot->addGraph();

    ui->plot->setBackground(QBrush(QColor(255, 255, 255)));
    ui->plot->yAxis->setLabel("温度  /℃ ");
    ui->plot->xAxis->setLabel("Time  /s ");
    ui->plot->xAxis->ticker()->setTickCount(11);//设刻度数
    ui->plot->yAxis->ticker()->setTickCount(10);//设刻度数
    ui->plot->xAxis->setTickLengthIn(10);//设主刻度显示长度;
    ui->plot->yAxis->setTickLengthIn(10);//设主刻度显示长度;
    ui->plot->xAxis->setSubTickLength(6);//设分刻度显示长度;
    ui->plot->yAxis->setSubTickLength(6);//设分刻度显示长度;

    ui->plot->xAxis->setTickPen(QPen(QColor(Qt::black)));//设主刻度颜色
    ui->plot->yAxis->setTickPen(QPen(QColor(Qt::black)));  //设主刻度颜色
    ui->plot->xAxis->setSubTickPen(QPen(QColor(Qt::black)));//设分刻度颜色
    ui->plot->yAxis->setSubTickPen(QPen(QColor(Qt::black)));//设分刻度颜色
    ui->plot->xAxis->setBasePen(QPen(QColor(Qt::black)));//设x轴线颜色
    ui->plot->yAxis->setBasePen(QPen(QColor(Qt::black)));//设y轴线颜色

    ui->plot->xAxis->setTickLabelColor(Qt::black);//设主刻度标签颜色
    ui->plot->yAxis->setTickLabelColor(Qt::black);//设主刻度标签颜色

    ui->plot->xAxis->setLabelColor(Qt::black);//设X轴标签颜色
    ui->plot->yAxis->setLabelColor(Qt::red);//设y轴标签颜色

    QFont ft;
    ft.setPixelSize(20);
    ui->plot->xAxis->setLabelFont(ft);
    ui->plot->yAxis->setLabelFont(ft);
    QFont ft_tick;
    ft_tick.setPixelSize(15);
    ui->plot->xAxis->setTickLabelFont(ft_tick);
    ui->plot->yAxis->setTickLabelFont(ft_tick);

    ui->plot->xAxis->setRange(0,600);//设定X轴范围
    ui->plot->yAxis->setRange(20,30);//设定X轴范围

    //表格
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//列宽自适应
    //ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);     //然后设置要根据内容使用宽度的列


    int row=ui->tableWidget->rowCount();
    int column=ui->tableWidget->columnCount();
    qDebug()<<row<<column;

    int i,j;
    for(i=0;i<row;i++)
    {
        for(j=0;j<column;j++)
        {
            ui->tableWidget->setItem(i,j,new QTableWidgetItem(""));
            if(j==column-1)ui->tableWidget->item(i,0)->setFlags(Qt::NoItemFlags);
            if(j==column-1)ui->tableWidget->item(i,1)->setFlags(Qt::NoItemFlags);
            if(j==column-1)ui->tableWidget->item(i,2)->setFlags(Qt::NoItemFlags);
            if(j==column-1)ui->tableWidget->item(i,6)->setFlags(Qt::NoItemFlags);
            if(j==column-1)ui->tableWidget->item(i,7)->setFlags(Qt::NoItemFlags);
            if(j==column-1)ui->tableWidget->item(i,8)->setFlags(Qt::NoItemFlags);
            if(j==column-1)ui->tableWidget->item(i,9)->setFlags(Qt::NoItemFlags);
            if(j==column-1)ui->tableWidget->item(i,10)->setFlags(Qt::NoItemFlags);
            //ui->tableWidget->item(row,column)->setFlags(Qt::ItemIsEnabled);

        }
    }

    //数据初始化

    buffer.buf.buf_tn=0;
    buffer.buf.buf_fr=0;
    buffer.buf.buf_rr=0;
    buffer.buf.buf_tc=0;
    buffer.buf.buf_tl=0;
    buffer.buf.buf_th=0;

    buffer.buf.buf_rr=buffer.system.system_rrl1+buffer.system.system_rrl2;// 比热容+修正   j/K

     qDebug()<<buffer.buf.buf_rr;


    //设置列表高度
    QStyledItemDelegate *delegate = new QStyledItemDelegate(this);
    ui->comboBox->setItemDelegate(delegate);
    ui->comboBox->setStyleSheet("QComboBox QAbstractItemView::item {min-height: 30px;}");


}

void MainWindow::test_new()
{
    if(buffer.data.sql_data.count()>0)//
    {

        int table_column=ui->tableWidget->columnCount();
        int column=buffer.data.sql_data.at(0).count();
        int row=buffer.data.sql_data.count();
        if(column==table_column)
        {
            for(int i=0;i<row;i++)
            {
                for(int j=0;j<column;j++)
                     ui->tableWidget->setItem(i,j,new QTableWidgetItem(buffer.data.sql_data.at(i).at(j)));


                ui->tableWidget->item(i,0)->setFlags(Qt::NoItemFlags);
                ui->tableWidget->item(i,1)->setFlags(Qt::NoItemFlags);
                ui->tableWidget->item(i,2)->setFlags(Qt::NoItemFlags);

                ui->tableWidget->item(i,7)->setFlags(Qt::NoItemFlags);
                ui->tableWidget->item(i,8)->setFlags(Qt::NoItemFlags);
                ui->tableWidget->item(i,9)->setFlags(Qt::NoItemFlags);
                ui->tableWidget->item(i,10)->setFlags(Qt::NoItemFlags);

                ui->tableWidget->item(i,6)->setText(QString("%1").arg(buffer.system.system_jrs));
                QString str=ui->tableWidget->item(i,0)->text();

                if(str.mid(0,3)!="cal")
                {
                    ui->tableWidget->item(i,7)->setText(QString("%1").arg(buffer.system.system_rrl1+buffer.system.system_rrl2));
                    double val=ui->tableWidget->item(i,8)->text().toDouble();
                    if(val>0)
                    {
                        ui->tableWidget->item(i,3)->setFlags(Qt::NoItemFlags);
                        ui->tableWidget->item(i,4)->setFlags(Qt::NoItemFlags);
                        ui->tableWidget->item(i,5)->setFlags(Qt::NoItemFlags);
                        ui->tableWidget->item(i,6)->setFlags(Qt::NoItemFlags);

                    }
                }
                else
                {
                    double val=ui->tableWidget->item(i,7)->text().toDouble();
                    if(val>0)
                    {
                        ui->tableWidget->item(i,3)->setFlags(Qt::NoItemFlags);
                        ui->tableWidget->item(i,4)->setFlags(Qt::NoItemFlags);
                        ui->tableWidget->item(i,5)->setFlags(Qt::NoItemFlags);
                        ui->tableWidget->item(i,6)->setFlags(Qt::NoItemFlags);

                    }
                 }
            }

        }

        ui->comboBox->setCurrentIndex(0);

    }
}

void MainWindow::on_test_sql_clicked()
{
    if(Dialog_sql::show(&buffer)==1)
    {
        test_new(); Dialog_msbox::show(0,0,"数据加载","Data loading","数据加载完成！");
    }
}

void MainWindow::on_test_id_clicked()
{
    int ret=Dialog_yp::show(&buffer);
    if(ret==1)
    {         
         mysql::query_test_all(buffer.info.test_id,&buffer);
         test_new();
    }
}

void MainWindow::on_test_set_clicked()
{
    Dialog_set::show(&buffer);
}

void MainWindow::on_test_exit_clicked()
{
    this->close();
}

double MainWindow::Lerp(double x0,double x1,double y0,double y1,double x)
{
    double dy = x1 - x0;
    return (x-x0) * ((y1 - y0) / dy) + y0;
}

void MainWindow::on_test_cal_clicked()
{
   QString str=ui->tableWidget->item(0,0)->text();
   if(str.mid(0,3)=="cal")
   {
        QVector<double>value;
        for(int i=0;i<6;i++)
        {
            double val=ui->tableWidget->item(i,7)->text().toDouble();
            if(val>0)value.append(val);
        }

        if(value.count()>=3)
        {
            double sum = std::accumulate(value.begin(), value.end(), 0.0);
            double mean =  sum / value.size();


            auto max = std::max_element(std::begin(value), std::end(value));//取容器内最大值
            auto min = std::min_element(std::begin(value), std::end(value));//取容器内最小值

            if(*max-*min<100)
            {
                buffer.system.system_rrl1=mean;
                buffer.buf.buf_rr=mean;
                mysql::INSERT_system(buffer.system);//存入数据库
                Dialog_msbox::show(1,0,"标定","calibration",QString("热容量标定成功！标定结果:%1 J/K\n最大值：%2\n最小值：%3")
                                   .arg(mean).arg(*max).arg(*min));
            }else
            {
                Dialog_msbox::show(1,0,"标定","calibration",QString("热容量标定失败！以下结果不符合标准\n最大值：%1\n最小值：%2\n差值：%3")
                                   .arg(*max).arg(*min).arg(*max-*min));
            }

        }else
        {
            Dialog_msbox::show(1,0,"标定","calibration",QString("热容量标定失败！标定试验需要3次以上数据。"));
        }

   }
   else
   {
     Dialog_msbox::show(1,0,"标定","calibration",QString("热容量标定失败！\n标定方法：历史数据->试验编号->cal001->载入->热容标定。"));
   }

}

void MainWindow::on_test_sum_clicked()
{
    Dialog_test::show(&buffer);
}

void MainWindow::on_test_save_clicked()//数据保存
{
    test_data data;
    data.data_id=buffer.info.test_id;

    for(int i=0;i<6;i++)
    {
        data.data_index=QString("%1").arg(i+1);
        data.data_t1  =ui->tableWidget->item(i,1)->text().toDouble();
        data.data_t2  =ui->tableWidget->item(i,2)->text().toDouble();
        data.data_sum =ui->tableWidget->item(i,3)->text().toDouble();
        data.data_tjw =ui->tableWidget->item(i,4)->text().toDouble();
        data.data_bjs =ui->tableWidget->item(i,5)->text().toDouble();
        data.data_jrs =ui->tableWidget->item(i,6)->text().toDouble();
        data.data_dtl =0;
        data.data_sdl =ui->tableWidget->item(i,7)->text().toDouble();
        data.data_zp  =ui->tableWidget->item(i,8)->text().toDouble();
        data.data_d1  =ui->tableWidget->item(i,9)->text();
        data.data_d2  =ui->tableWidget->item(i,10)->text();

        mysql::INSERT_test_data(data);
    }

    Dialog_msbox::show(1,0,"保存数据","Save",QString("编号:%1 试验数据已保存！").arg(buffer.info.test_id));

}

void  MainWindow::get_bush()
{
    for(int i=1;i<8;i++)
    {
        go_logo[i]->gif_run=false;
        go_logo[i]->gif_start=90;
        go_logo[i]->set_gif(0);
        go_logo[i]->set_val(10);
    }
}


void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    buffer.data.data_index=QString("%1").arg(index+1);
    mysql::query_test_temp(&buffer);


    //刷新曲线数据
    auto max = std::max_element(std::begin(buffer.buf.buf_ct), std::end(buffer.buf.buf_ct));//取容器内最大值
    auto min = std::min_element(std::begin(buffer.buf.buf_ct), std::end(buffer.buf.buf_ct));//取容器内最小值
    ui->plot->yAxis->setRange(*min-0.5,*max+0.5);
    ui->plot->xAxis->setRange(0,buffer.buf.buf_ci.count()+60);

    ui->plot->graph(0)->setData(buffer.buf.buf_ci,buffer.buf.buf_ct);
    ui->plot->show();
    ui->plot->replot();

}

void MainWindow::on_ctrl_clicked()
{
    test_check  mycheck(&buffer,this);
    mycheck.exec();

}
